package com.guojian.common.listener;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import org.springframework.context.ApplicationEvent;
import org.springframework.core.ResolvableType;

import com.google.common.collect.Lists;
import com.guojian.common.http.Test;

import cn.hutool.core.util.ClassUtil;

public class EventPublish {

	private final List<MyTestListener<? extends ApplicationEvent>> listeners = Lists.newArrayList();

	public void registerListener(MyTestListener<? extends ApplicationEvent> listener) {
		this.listeners.add(listener);
	}

	/**
	 * 发布事件
	 */

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void multicastEvent(ApplicationEvent event) {
		for (MyTestListener myTestListener : listeners) {

			/*Object source = event.getSource();
			Class<?> sourceType = (source != null ? source.getClass() : null);*/
			ResolvableType eventType = ResolvableType.forClass(myTestListener.getClass()).as(MyTestListener.class).getGeneric();

			System.out.println(eventType.getRawClass());

			System.out.println(event.getClass().isAssignableFrom(eventType.getRawClass()));

			if (event.getClass().isAssignableFrom(eventType.getRawClass())) {
				myTestListener.onEvent(event);
			}

		}
	}

	public static void main(String[] args) {
		//System.out.println(ClassUtil.getTypeArgument(UserRegisterListener.class));
		
		test();
		
	}

	public static void test() {
		/*String source = "my name is 事件源";
		UserRegisterEvent event = new UserRegisterEvent(source);
		
		UserLoginEvent loginEvent = new UserLoginEvent(source);
		
		EventPublish publish = new EventPublish();
		publish.registerListener(new UserRegisterListener());
		publish.multicastEvent(event);
		
		publish.multicastEvent(loginEvent);*/

		System.out.println(ResolvableType.forClass(UserRegisterListener.class));

		System.out.println(ResolvableType.forClass(UserRegisterListener.class).as(MyTestListener.class));

		ResolvableType eventType = ResolvableType.forClass(UserRegisterListener.class).as(MyTestListener.class).getGeneric();
		System.out.println(eventType);

		System.out.println(ResolvableType.forClass(MyTestListener.class, UserRegisterListener.class).hasGenerics());

		Type[] interfaces = UserRegisterListener.class.getGenericInterfaces();

		for (Type type : interfaces) {
			if (type instanceof ParameterizedType) {
				ParameterizedType ptype = (ParameterizedType) type;
				Type[] atypes = ptype.getActualTypeArguments();
				for (Type type2 : atypes) {
					System.out.println(type2);
				}
			}
		}
	}

}
